#include "ip_filter.h"

namespace secsmart_tcpip
{
void IpFilter::add_rule(const IpFilterRule &rule)
{
    if (rule.type == RULE_TYPE_BACKLIST) {
        black_rules_[rule.rule_id] = rule;
    } else {
        white_rules_[rule.rule_id] = rule;
    }
}

void IpFilter::del_rule(uint32_t rule_id)
{
    if (black_rules_.find(rule_id) != black_rules_.end()) {
        black_rules_.erase(rule_id);
    } else if (white_rules_.find(rule_id) != white_rules_.end()) {
        white_rules_.erase(rule_id);
    }
}

bool IpFilter::filter_ip(IPAddress &ip)
{
    // 不进行过滤
    if (mode_ == IP_FILTER_MODE_NULL) {
        return false;
    }

    // 黑名单过滤
    if (mode_ == IP_FILTER_MODE_BACKLIST) { 
        auto it = black_rules_.begin();
        for (; it != black_rules_.end(); it++) {
            if (it->second.enable == false) {
                continue;
            }
            if (it->second.ip_range.check(ip)) {
                return true; // 命中表项过滤该IP地址
            }
        }
        return false;
    } else { // 白名单过滤
        auto it = white_rules_.begin();
        for (; it != white_rules_.end(); it++) {
            if (it->second.enable == false) {
                continue;
            }
            if (it->second.ip_range.check(ip)) {
                return false; // 命中表项需要处理
            }
        }
        return true;
    }    
}

uint32_t IpFilter::get_rule_num(uint8_t type)
{
    if (type == RULE_TYPE_BACKLIST) {
        return black_rules_.size();
    } else if (type == RULE_TYPE_WHITELIST) {
        return white_rules_.size();
    }
    return 0;
}

}

